package models

import (
	"time"

	"github.com/astaxie/beego/orm"
)

type User struct {
	Id       int
	Username string `form:"username"`
	Password string `form:"password"`
	Created  time.Time
	Update   time.Time
}

type GeneralResp struct {
	Code  int         `json:"code"`
	Data  interface{} `json:"data"`
	Error string      `json:"error"`
}

func (u *User) TableName() string {
	return "cms_user"
}

func init() {
	orm.RegisterModel(&User{})
}

//查询单个用户内容
func GetUserById(id int) *User {
	if id == 0 {
		return nil
	}

	o := orm.NewOrm()
	user := User{}
	user.Id = id
	err := o.Read(&user)

	if err == orm.ErrNoRows {
		return nil
	} else if err == orm.ErrMissPK {
		return nil
	}

	return &user
}

//查询用户列表
func GetUserList() []User {
	o := orm.NewOrm()
	var data []User
	//查询所有用户所有内容
	_, _ = o.QueryTable("cms_user").All(&data)
	return data
}

//新增用户
func AddUserData(username string, password string) int64 {
	o := orm.NewOrm()
	var user = User{}
	var t = time.Now()
	user.Username = username
	user.Password = password
	user.Created = t
	user.Update = t
	id, _ := o.Insert(&user)
	return id
}

//根据ID删除用户
func DelUserById(id int) int64 {
	o := orm.NewOrm()
	var user = User{}
	user.Id = id
	_, err := o.Delete(&user)
	if err != nil {
		return 1
	} else {
		return 0
	}

}

//根据ID修改用户资料
func UpdateUser(username string, password string, id int) error {
	o := orm.NewOrm()
	var user = User{}
	user.Id = id
	user.Username = username
	user.Password = password
	user.Update = time.Now()
	_, err := o.Raw("update cms_user set username = ?,password = ?,`update` = ? where id = ?", user.Username, user.Password, user.Update, user.Id).Exec()
	return err
}
